from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
import json

APP_ROOT = "./"

# 初始化应用
app = Flask(__name__)
app.config['SECRET_KEY'] = 'wol-key'
CORS(app, resources={r"/*": {"origins": "*"}})  # 允许跨域

@app.route('/computer_lists', methods=['GET'])
def return_computer_lists():
    with open(APP_ROOT+"/data/config","r") as f:
        config_json = json.load(f)["computer_cfg"]
    for computer_cfg in config_json:
        del computer_cfg["password"]
    print(config_json)
    return jsonify(config_json), 200

@app.route('/computer/icon', methods=['GET'])
def return_user_icon():
    computer_id = int(request.args.get("id"))
    with open(APP_ROOT+"/data/config","r") as f:
        config_json = json.load(f)["computer_cfg"]
    for computer_cfg in config_json:
        if computer_cfg["id"] == computer_id:
            return send_file(computer_cfg["icon"], mimetype='image/jpeg')
    return "找不到", 404

@app.route('/wake', methods=['POST'])
def wakeup_computer():
    computer_id = int(request.get_json()['computer_id'])
    password = request.get_json()['password']
    if not computer_id or not password:
        return "验证失败", 401
    with open(APP_ROOT+"/data/config","r") as f:
        config_json = json.load(f)["computer_cfg"]
    for computer_cfg in config_json:
        if computer_id == computer_cfg["id"] and password == computer_cfg["password"]:
            # TODO 在这里执行唤醒程序
            return "OK", 200
    return "验证失败", 401


if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)
